package com.asp.controller;

import com.asp.constant.MessageConstant;
import com.asp.exception.FileEmptyException;
import com.asp.result.Result;
import com.asp.utils.AliOSSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * author:          ndg
 * date:            2024/1/3
 */
@RestController
@Slf4j
@Api(tags = "通用接口")
@RequestMapping("/user/common")
public class CommonController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Result upload(MultipartFile avatar) {
        log.info("文件上传：{}", avatar);

        try {
            if (avatar == null) {
                throw new FileEmptyException(MessageConstant.FILE_EMPTY);
            }
            //  原始文件名
            String originalFilename = avatar.getOriginalFilename();
            // 获取原始文件的后缀名
            String extension = null;
            if (originalFilename != null) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            //构造新文件名称
            String objectName = UUID.randomUUID() + extension;
            //文件的请求路径
            String filePath = aliOSSUtils.upload(avatar.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败" + e.getMessage());
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
